<template>
    <view>
        <!-- <view :style="{display:isNone}"> -->
        <u-navbar
            :border-bottom="false"
            :back-text="agoraRoomData.section_name"
            :immersive="istrue"
            :background="backgroundColor"
        >
            <view class="search-wrap">
                <view class="time"></view>
                <!-- 大课班头部样式 -->
                <view class="right_item2" v-if="agoraRoomData.class_type == 1">
                    <view v-if="isConnect" class="right_l2">
                        <view class="break" @click="breakMic()">
                            <u-icon
                                name="phone-fill"
                                size="28"
                                color="#fff"
                            ></u-icon>
                            <text>断开</text>
                        </view>
                        <u-icon
                            name="mic"
                            v-if="openMic"
                            size="40"
                            @click="choseMic(false)"
                            color="#fff"
                            style="margin-left: 35rpx; margin-right: 20rpx"
                        ></u-icon>
                        <u-icon
                            name="mic-off"
                            v-else
                            size="40"
                            @click="choseMic(true)"
                            style="margin-left: 35rpx; margin-right: 20rpx"
                            color="#fff"
                        ></u-icon>
                        <u-icon
                            name="camera"
                            v-if="openCamera"
                            @click="choseVideo(false)"
                            size="40"
                            color="#fff"
                            style="margin-right: 16rpx"
                        ></u-icon>
                        <image
                            v-else
                            src="../../static/images/course/close_cam.png"
                            @click="choseVideo(true)"
                            style="
                                margin-right: 16rpx;
                                height: 40rpx;
                                width: 40rpx;
                            "
                        ></image>
                    </view>
                    <view
                        class="right_l"
                        v-else
                        :class="[isOccupy ? 'Occupy' : 'noOccupy']"
                        @click="connectMic(isOccupy)"
                    >
                        <u-icon
                            name="phone-fill"
                            size="28"
                            color="#fff"
                        ></u-icon>
                        <text>连麦</text>
                    </view>
                </view>
                <!-- 小课班头部 -->
                <view class="right_item" v-else>
                    <u-icon
                        name="mic"
                        v-if="openMic"
                        size="40"
                        @click="choseMic(false)"
                        color="#fff"
                    ></u-icon>
                    <u-icon
                        name="mic-off"
                        v-else
                        size="40"
                        @click="choseMic(true)"
                        color="#fff"
                    ></u-icon>
                    <u-icon
                        v-if="openCamera"
                        name="camera"
                        size="40"
                        color="#fff"
                        @click="choseVideo(false)"
                    ></u-icon>
                    <image
                        v-else
                        src="../../static/images/course/close_cam.png"
                        @click="choseVideo(true)"
                        class="sheet_icon"
                    ></image>
                </view>
            </view>
        </u-navbar>
        <!-- </view> -->

        <big-class
            v-if="agoraRoomData.class_type == 1"
            :teach_name="teacher_obj.userName"
            :isShow="isShow"
            :save_room_msg="save_room_msg"
            :isOwn="isOwn"
            :my_name="agoraRoomData.user_name"
            :teach_id="teacher_obj.uid"
            @showMeth="showMeth"
            :isOccupy="isOccupy"
            :videoIdList="videoIdList"
        ></big-class>
        <small-class
            v-else-if="agoraRoomData.class_type == 2"
            :save_room_msg="save_room_msg"
            :isShow="isShow"
            :teach_id="teacher_obj.uid"
            @showMeth="showMeth"
            :videoIdList="videoIdList"
            :my_name="agoraRoomData.user_name"
            :openCamera="openCamera"
        ></small-class>
        <one-room
            v-else
            @showMeth="showMeth"
            ref="child"
            :videoIdList="videoIdList"
            :isShow="isShow"
            :my_name="agoraRoomData.user_name"
            :teach_name="teacher_obj.userName"
        ></one-room>
        <view class="time_bar" style="color: #ffffff">
            <view class="s_circle"></view>
            <view>{{ com_time }}</view>
        </view>
        <view class="chose_content">
            <view class="item" @click="chose(0)">
                <view class="text" :class="[choseId == 0 ? 'font_color' : '']"
                    >白板</view
                >
                <view
                    class="bar"
                    :class="[choseId == 0 ? 'bg_color' : '']"
                ></view>
            </view>
            <view class="item" @click="chose(1)">
                <view class="text" :class="[choseId == 1 ? 'font_color' : '']"
                    >聊天</view
                >
                <view
                    class="bar"
                    :class="[choseId == 1 ? 'bg_color' : '']"
                ></view>
            </view>
        </view>
        <white-board
            ref="wboard"
            @sendRoomId="sendRoomId"
            :class="[choseId == 0 ? '' : 'hidden']"
            :whiteboard="whiteboard"
            :config="config"
            :live_obj="live_obj"
            :isShow="showControl"
            :options="agoraRoomData"
        ></white-board>
        <view class="chat_wrap" :class="[choseId == 1 ? '' : 'hidden']">
            <cul-chat
                anotherAvatar="/static/images/course/live_dashang.png"
                meAvatar="/static/images/course/live_dashang.png"
                :anotherMsg="anotherMsg"
                :noTalk="noTalk"
                :sid="agoraRoomData.sid"
                @destoryRoom="destoryRoom"
                @submit="sendMsg"
            ></cul-chat>
        </view>
    </view>
</template>

<script>
import OneRoom from "./component/1v1.vue";
import BigClass from "./component/BigClass.vue";
import SmallClass from "./component/SmallClass.vue";
import culChat from "./component/cul-chat/cul-chat.vue";
import WhiteBoard from "./component/WhiteBoard.vue";
import AgoraRTC from "./agoraSdk/agoraRTCfunct.js";
import AgoraRTM from "./agoraSdk/agoraRTMfunct.js";
import { mapState, mapGetters } from "vuex";
export default {
    components: {
        OneRoom,
        WhiteBoard,
        culChat,
        BigClass,
        SmallClass,
    },
    data() {
        return {
            isOwn: false, //是否是自己
            isNone: "none",
            istrue: false,
            showControl: false,
            isConnect: false, //用户是否链接
            isOccupy: false, //大课班麦是否占用
            openCamera: true, //控制摄像头
            openMic: true, //控制麦克风
            backgroundColor: {
                backgroundColor: "#303133",
            },

            choseId: 0,
            config: {}, //声网配置信息
            myId: "",
            videoIdList: [],

            agora: {
                appID: "149f7636178140d5821bf0d2b61a480b", //appid
                channel: "", //房间频道
                uid: "", //用户uid
                token: "", // rtcToken
            },
            agora_rtm: {
                channelName: "",
                uid: "", //用户uid
                token: "", // rtmToken
            },

            user_token: "", //第三方接口返回
            roomID: "", //第三方接口返回roomid

            anotherMsg: {}, //存放频道消息
            teacher_obj: {}, //存放老师数据

            live_obj: {},

            noTalk: false, //是否禁言
            isShow: "",

            time: 0,
            now_time: 0,
            flag: null,

            save_room_msg: [],

            whiteboard: false, //白板控制

            control_msg: {
                enableAudio: 1,
                enableChat: 1,
                enableVideo: 1,
                grantBoard: 0,
            },

            userId: "", //当前用户userid

            set_lockBoard: 1, //默认进入白板缩放

            agoraRoomData: {},
        };
    },
    computed: {
        ...mapState({
            getCurrentPlayItem: (state) => state.course.currentPlayItem,
        }),
        ...mapGetters({
            userInfo: "user/getUserInfo",
        }),
        com_time: function () {
            var remain = (this.now_time - this.time) / 1000;
            var h =
                Math.floor(remain / 3600) < 10
                    ? "0" + Math.floor(remain / 3600)
                    : Math.floor(remain / 3600);
            var m =
                Math.floor((remain / 60) % 60) < 10
                    ? "0" + Math.floor((remain / 60) % 60)
                    : Math.floor((remain / 60) % 60);
            var s =
                Math.floor(remain % 60) < 10
                    ? "0" + Math.floor(remain % 60)
                    : Math.floor(remain % 60);
            return h + ":" + m + ":" + s;
        },
    },
    watch: {
        set_lockBoard(val) {
            setTimeout(() => {
                if (val == 1) {
                    this.$refs.wboard.followBoard(true);
                } else if (val == 0) {
                    this.$refs.wboard.followBoard(false);
                }
            }, 500);
        },
    },
    onLoad(option) {
        this.$edu.api.getAgoraRoomMsg(option.id).then((res) => {
            const { data } = res;
            // this.getStudyRecord(); //生成学习记录
            if (data.course_live_type == 1) {
                this.live_obj = {
                    type: 2,
                    role: 2,
                };
            } else if (data.course_live_type == 2) {
                this.live_obj = {
                    type: 1,
                    role: 2,
                };
            } else if (data.course_live_type == 3) {
                this.showControl = true;
                this.live_obj = {
                    type: 0,
                    role: 2,
                };
            }
            this.whiteboard = data.course_live_type == 3 ? true : false;
            this.getConfig(); //获取声网配置

            this.agoraRoomData = {
                id: this.getCurrentPlayItem.course_id,
                sid: option.id,
                class_type: data.info.course_live_type,
                user_id: data.info.user_id,
                teacher_id: data.info.teacher_id,
                room_no: data.info.room_no,
                identity: data.info.identity,
                section_name: data.info.section_name,
                user_name: this.userInfo.nick_name,
                appid: data.config.appid,
            };
        });
    },
    onBackPress() {
        if (AgoraRTM.rtm.client == null || AgoraRTC.rtc.client == null) return;
        AgoraRTC.leave(); //离开频道
        AgoraRTC.unpublish(AgoraRTC.rtc); //取消发布
        AgoraRTM.loginOut(); //离开聊天室
        this.$refs.wboard.handGoBack(); //离开白板房间
    },
    beforeDestroy() {
        this.flag = clearInterval(this.flag);
    },
    methods: {
        destoryRoom(data) {
            AgoraRTC.leave(); //离开频道
            AgoraRTC.unpublish(AgoraRTC.rtc); //取消发布
            AgoraRTM.loginOut(); //离开聊天室
            this.$refs.wboard.handGoBack(); //离开白板房间
            this.flag = clearInterval(this.flag);
        },
        showMeth(data) {
            this.isNone = "";
            setTimeout(() => {
                this.isNone = "none";
            }, 3000);
        },
        //获取直播间信息
        sendRoomId(data) {
            this.user_token = data.user_token;
            this.roomID = data.roomID;
            var that = this;
            var url = `https://api.agora.io/edu/v1/apps/${this.agora.appID}/room/${data.roomID}`;
            var requestInit = {
                method: "GET",
                headers: {
                    "content-type": "application/json",
                    token: data.user_token,
                    Authorization:
                        "Basic OTcxMWE0OTYxZTQ3NDlkNzgxZjdjZTRjZGFmODIyMWY6ZDIxYTViMThmZmQzNDg3MjlkMzAwNWU4MTZhZTQxYTA=",
                },
            };
            window
                .fetch(url, requestInit)
                .then(function (response) {
                    return response.json();
                })
                .then(function (json) {
                    var room_result = json.data;
                    that.save_room_msg = json.data.room.coVideoUsers;
                    that.set_lockBoard = json.data.room.lockBoard;
                    if (json.data.room.coVideoUsers.length != 0) {
                        json.data.room.coVideoUsers.forEach((el, key) => {
                            if (el.role == 1) {
                                that.teacher_obj = el;
                            }
                        });
                    }
                    that.userId = room_result.user.userId;
                    that.agora.uid = room_result.user.uid;
                    that.agora.token = room_result.user.rtcToken;
                    that.agora.channel = room_result.room.channelName;
                    that.agora_rtm.uid = room_result.user.uid.toString();
                    that.agora_rtm.token = room_result.user.rtmToken;
                    that.agora_rtm.channelName = room_result.room.channelName;
                    AgoraRTC.agoraFunction(that, that.agora); //调用视频
                    AgoraRTM.agoraFunction(that, that.agora_rtm); //调用聊天室
                    that.startTime(json.data.room.startTime);
                });
        },
        again_msg() {
            var that = this;
            var url = `https://api.agora.io/edu/v1/apps/${this.agora.appID}/room/${this.roomID}`;
            var requestInit = {
                method: "GET",
                headers: {
                    "content-type": "application/json",
                    token: this.user_token,
                    Authorization:
                        "Basic OTcxMWE0OTYxZTQ3NDlkNzgxZjdjZTRjZGFmODIyMWY6ZDIxYTViMThmZmQzNDg3MjlkMzAwNWU4MTZhZTQxYTA=",
                },
            };
            window
                .fetch(url, requestInit)
                .then(function (response) {
                    return response.json();
                })
                .then((json) => {
                    if (json.data.room.coVideoUsers.length != 0) {
                        json.data.room.coVideoUsers.forEach((el, key) => {
                            if (el.role == 1) that.teacher_obj = el;
                        });
                    }
                    that.save_room_msg = json.data.room.coVideoUsers;
                });
        },
        startTime(time) {
            this.time = time;
            this.flag = setInterval(() => {
                var date = new Date();
                var now_time = Date.parse(date);
                this.now_time = now_time;
            }, 1000);
        },
        addView(id) {
            if (id == this.myId || this.videoIdList.indexOf(id) != -1) return;
            const list = this.videoIdList;
            list.push(id);
            this.videoIdList = list;
            if (
                this.agoraRoomData.class_type == 1 &&
                this.videoIdList.length > 1
            ) {
                this.isOccupy = true;
            }
        },
        deleteView(id) {
            const index = this.videoIdList.indexOf(id);
            if (index != -1) {
                const list = this.videoIdList;
                list.splice(index, 1);
                this.videoIdList = list;
            }
        },
        chose(id) {
            this.choseId = id;
        },
        //获取声网配置信息
        getConfig() {
            this.$edu.api.getAgoraConfig().then((res) => {
                this.config = res.data;
            });
        },
        // 音视频白板控制请求接口
        controlSwitch(data) {
            var that = this;
            var body = data;
            var url = `https://api.agora.io/edu/v1/apps/${this.agora.appID}/room/${this.roomID}/user/${that.userId}`;
            var requestInit = {
                method: "POST",
                headers: {
                    "content-type": "application/json",
                    token: this.user_token,
                    Authorization:
                        "Basic OTcxMWE0OTYxZTQ3NDlkNzgxZjdjZTRjZGFmODIyMWY6ZDIxYTViMThmZmQzNDg3MjlkMzAwNWU4MTZhZTQxYTA=",
                },
                body: JSON.stringify(body),
            };
            window
                .fetch(url, requestInit)
                .then(function (response) {
                    return response.json();
                })
                .then(function (json) {
                    console.log(json);
                });
        },
        //连麦与断脉请求接口
        control_mic_type(data) {
            var that = this;
            var url = `https://api.agora.io/edu/v1/apps/${this.agora.appID}/room/${this.roomID}/covideo`;
            var body = { type: data };
            var requestInit = {
                method: "POST",
                headers: {
                    "content-type": "application/json",
                    token: this.user_token,
                    Authorization:
                        "Basic OTcxMWE0OTYxZTQ3NDlkNzgxZjdjZTRjZGFmODIyMWY6ZDIxYTViMThmZmQzNDg3MjlkMzAwNWU4MTZhZTQxYTA=",
                },
                body: JSON.stringify(body),
            };
            window
                .fetch(url, requestInit)
                .then(function (response) {
                    return response.json();
                })
                .then(function (json) {
                    that.$u.toast("已发送申请");
                });
        },
        // 控制是否开启摄像头
        choseVideo(type) {
            this.openCamera = type;
            type == true
                ? AgoraRTC.rtc.localStream.unmuteVideo()
                : AgoraRTC.rtc.localStream.muteVideo();
            if (type == true) {
                this.control_msg.enableVideo = 1;
                this.controlSwitch(this.control_msg);
            } else {
                this.control_msg.enableVideo = 0;
                this.controlSwitch(this.control_msg);
            }
        },
        // 控制是否开启麦克风
        choseMic(type) {
            this.openMic = type;
            type == true
                ? AgoraRTC.rtc.localStream.unmuteAudio()
                : AgoraRTC.rtc.localStream.muteAudio();
            if (type == true) {
                this.control_msg.enableAudio = 1;
                this.controlSwitch(this.control_msg);
            } else {
                this.control_msg.enableAudio = 0;
                this.controlSwitch(this.control_msg);
            }
        },
        sendMsg(data) {
            var message = {
                message: data.message,
                userName: data.user_name,
                userAvatar: data.user_avatar,
            };
            var obj = {
                data: message,
                cmd: 1,
            };
            AgoraRTM.sendMsg(JSON.stringify(obj));
        },
        //接受来自频道的消息
        getMsg(data) {
            let anotherMsg = {
                isme: false,
                data: data.text,
                userId: data.userId,
                user_name: data.user_name,
                user_avatar: data.user_avatar,
            };
            this.anotherMsg = anotherMsg;
        },
        // 直播连麦
        connectMic(type) {
            var that = this;
            if (type == false) {
                // 发送连麦申请
                that.control_mic_type(1);
            } else {
                this.$u.toast("被占用");
            }
        },
        // 开始连麦
        startMic() {
            AgoraRTC.createStream();
            var channelAttributes = { data: "host" };
            AgoraRTM.rtm.client.addOrUpdateChannelAttributes(
                this.agora_rtm.channelName,
                channelAttributes,
                {
                    enableNotificationToChannelMembers: true,
                }
            );
            this.isOwn = true;
            this.isOccupy = true;
            this.isConnect = true;
        },
        //断麦
        breakMic() {
            var that = this;
            AgoraRTC.unpublish(AgoraRTC.rtc);
            AgoraRTC.rtc.client.setClientRole("audience");
            var channelAttributes = {
                data: "audience",
            };
            AgoraRTM.rtm.client.addOrUpdateChannelAttributes(
                this.agora_rtm.channelName,
                channelAttributes,
                {
                    enableNotificationToChannelMembers: true,
                }
            );
            that.control_mic_type(6);
        },
        changeOccupy(type) {
            if (type == "host") {
                this.isOccupy = true;
            } else if (type == "audience") {
                this.isOccupy = false;
                this.isConnect = false;
            }
        },
        control(obj) {
            console.log("局部控制");
            this.noTalk = obj.enableChat == 0 ? true : false; //是否禁言
            obj.enableVideo == 0
                ? AgoraRTC.rtc.localStream.muteVideo()
                : AgoraRTC.rtc.localStream.unmuteVideo(); //是否打开摄像头
            obj.enableAudio == 0
                ? AgoraRTC.rtc.localStream.muteAudio()
                : AgoraRTC.rtc.localStream.unmuteAudio(); //是否开麦
            this.openCamera = obj.enableVideo == 0 ? false : true; //控制用户是否打开摄像头
            this.openMic = obj.enableAudio == 0 ? false : true; //控制用户是否开麦
            obj.grantBoard == 1
                ? this.$refs.wboard.setBoard(true)
                : this.$refs.wboard.setBoard(false); //控制白板
            obj.grantBoard == 1
                ? (this.showControl = true)
                : (this.showControl = false); //控制白板
        },
        allControl(obj) {
            console.log("整体控制");
            this.noTalk = obj.muteAllChat == 1 ? true : false; //是否全体禁言
            obj.lockBoard == 1
                ? this.$refs.wboard.followBoard(true)
                : this.$refs.wboard.followBoard(false); //是否跟随白板视角
        },
        roleControl(obj) {
            this.isShow = obj.enableVideo == 0 ? false : true; //主播端是否开启摄像头
        },
        // 生成学习记录
        getStudyRecord() {
            this.$edu.api
                .createCourseRecord({
                    course_id: this.agoraRoomData.id,
                    section_id: this.agoraRoomData.sid,
                    current_time: this.time,
                })
                .then((res) => {});
        },
    },
};
</script>

<style lang="scss" scoped>
.hidden {
    display: none;
}
.search-wrap {
    display: flex;
    align-items: center;
    flex: 1;
    padding-right: 10rpx;
    justify-content: space-between;

    .time {
        font-size: 32rpx;
        color: #303133;
    }

    .right_item {
        /* #ifdef MP-WEIXIN */
        width: 27%;
        /* #endif */

        /* #ifndef MP-WEIXIN */
        width: 18%;
        /* #endif */

        display: flex;
        justify-content: space-between;

        .sheet_icon {
            height: 40rpx;
            width: 40rpx;
        }
    }

    .right_item2 {
        overflow: hidden;
        .right_l {
            height: 45rpx;
            width: 120rpx;
            border-radius: 23rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            text {
                font-size: 26rpx;
                color: #ffffff;
                line-height: 45rpx;
            }
        }
        .right_l2 {
            display: flex;
            .break {
                height: 45rpx;
                width: 120rpx;
                border-radius: 23rpx;
                background: #f54030;
                display: flex;
                justify-content: center;
                text {
                    font-size: 26rpx;
                    color: #ffffff;
                    line-height: 45rpx;
                }
            }
        }
    }
}

.time_bar {
    height: 72rpx;
    width: 100%;
    background-color: #303133;
    display: flex;
    color: #ffffff;
    font-size: 26rpx;
    align-items: center;
    letter-spacing: 1rpx;
    .s_circle {
        height: 12rpx;
        width: 12rpx;
        background-color: #67c23a;
        margin-right: 10rpx;
        margin-left: 30rpx;
        border-radius: 6rpx;
    }
}

.chose_content {
    height: 80rpx;
    width: 100%;
    background-color: white;
    display: flex;
    overflow: hidden;
    .item {
        height: 100%;
        width: 50%;
        text-align: center;
        font-size: 30rpx;
        color: #606266;
        overflow: hidden;
        .text {
            height: 74rpx;
            line-height: 74rpx;
        }
        .bar {
            height: 6rpx;
            width: 40rpx;
            margin: 0 auto;
            border-radius: 4rpx;
        }
    }
}
.chat_wrap {
    width: 100%;
    height: calc(100vh - 740rpx);
    // height: calc(100vh - 700rpx);
    background-color: #f7f7f7;
}
.font_color {
    @include text_color();
}
.bg_color {
    @include bg_color();
}
.noOccupy {
    background: #67c23a;
}
.Occupy {
    background-color: #606266;
}
</style>
